<template>
  <div class="uploadimg">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img
        v-if="value"
        :src="value"
        class="avatar"
        v-imgerror="errorImg"
        @click.stop="isShow = true"
      />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <!-- 关闭按钮 -->
    <div class="close" @click="del" v-if="value">X</div>
    <!-- 查看大图 -->
    <el-dialog :visible.sync="isShow" title="大图预览" width="400px">
      <img style="width:100%;" :src="value" v-imgerror="errorImg" alt="" />
    </el-dialog>
    <!-- 进度条 -->
    <transition name="fade">
      <el-progress
        v-if="showProgress"
        :percentage="percentage"
        style="width:178px;"
      ></el-progress>
    </transition>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDNXR8bpeSF1JL8EyZopxRfdHgqGUeuEn8',
  SecretKey: 'HJ9mAbQEn7jgjY9swEI6yAamk7MN8hty'
})
export default {
  name: 'Uploadimg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      errorImg: require('@/assets/common/head.jpg'),
      showProgress: false,
      isShow: false,
      percentage: 0 // 0-100
    }
  },
  methods: {
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 自定义上传
    httpRequest (data) {
      this.percentage = 0
      this.showProgress = true
      cos.putObject(
        {
          Bucket: 'dhf481229-1305249343' /* 存储桶 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: data.file.uid + '' /* 标识 */,
          StorageClass: 'STANDARD', // 固定值
          Body: data.file, // 上传文件对象  file文件对象
          onProgress: progressData => {
            // 上传进度，实时返回上传文件进度
            this.percentage = +(progressData.percent * 100).toFixed(2)
            if (progressData.percent === 1) {
              setTimeout(() => {
                this.showProgress = false
              }, 2000)
            }
            // console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          // 上传成功或者失败处理
          // err为空就是成功，err有值就是失败了
          // data就是上传成功后腾讯云返回的数据（上传文件地址）
          if (!err) {
            this.$emit('input', 'http://' + data.Location)
          }
        }
      )
    },
    // 删除
    del () {
      this.$emit('input', '')
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.uploadimg {
  position: relative;
  width: 178px;
  height: 195px;
  &:hover {
    .close {
      display: block;
    }
  }
  .close {
    position: absolute;
    top: 5px;
    right: 10px;
    cursor: pointer;
    display: none;
  }
}
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
